package com.mxprojects.io
{
	import com.mxprojects.gui.DefaultDialog;
	import com.mxprojects.language.Language;
	import com.mxprojects.language.Word;
	
	import flash.events.DataEvent;
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.FileFilter;
	import flash.net.FileReference;
	import flash.net.FileReferenceList;
	import flash.net.URLRequest;
	
	public class FileUploader
	{
		public static const IMAGE_SPACER:String = "-"; //goes between the salt and the image name
		public static const ADD_FILE:String = "add"; //if you change this here you need to change in transfer.php
		public static const REMOVE_FILE:String = "remove";
		
		public var totalFilesSelected:int = 0;
		
		private var imageTypes:FileFilter;
		private var theFiles:FileReferenceList = new FileReferenceList();
		//private var totalDataToTransfer:int = 0;
		//private var currentDataTransfered:int = 0;
		//private var progress:Dictionary = new Dictionary();
		private var selectedFiles:Array;
		private var showProgress:Boolean;
		private var maxUploadFileSize:int; //in KB
		private var maxNumberOfFiles:int;
		private var onSelect:Function;
		private var showStageOnErrorClose:Boolean;
		private var uploadURL:URLRequest;

		public function FileUploader(filesSelected:Function, showProgress:Boolean = true, maxUploadFileSize:int = 300, maxNumberOfFiles:int = 3, maxWidth:int = 2880, maxHeight:int = 2880, subDirectory:String = "", showStageOnErrorClose:Boolean = false){	
			//setup the stuff
			this.maxUploadFileSize = maxUploadFileSize;
			this.maxNumberOfFiles = maxNumberOfFiles;
			this.showProgress = showProgress;
			this.onSelect = filesSelected;
			this.showStageOnErrorClose = showStageOnErrorClose;
						
			//setup the URL
			var dataToSend:Object = new Object();
			dataToSend.username = BoardCookie.getUser();
			dataToSend.password = BoardCookie.getPassword();
			dataToSend.actionType = ADD_FILE;
			dataToSend.spacer = IMAGE_SPACER;
			dataToSend.maxWidth = maxWidth;
			dataToSend.maxHeight = maxHeight;
			dataToSend.abImgDir = Config.ABSOLUTE_INSTALL_PATH + Config.IMAGE_DIRECTORY + subDirectory;
			
			//tell the server handler we need to make us a URL
			var serverHandler:ServerHandler = new ServerHandler();
			uploadURL = serverHandler.transmitData("transfer.php", dataToSend, false);
			
			//setup the image types with locale
			imageTypes = new FileFilter(maxNumberOfFiles + " " + Language.main(Word.IMAGE) + " " + Language.main(Word.MAXIMUM) + " (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg; *.jpeg; *.gif; *.png");
			
			//setup the listeners
			theFiles.addEventListener(Event.SELECT, fileSelect, false, 0, true);
		}
		
		/****************************************************************** 
		 * YOU MUST PASS SOMETHING TO FIRE THIS FUNCTION TO UPLOAD ANYTHING 
		 ******************************************************************/
		
		public function setupUploadButton(event:MouseEvent):void {
			//open the browse window
			if(totalFilesSelected < maxNumberOfFiles){
				theFiles.browse(new Array(imageTypes));
			}else{
				//tell them they have already attached the max number
				DefaultDialog.show(Language.main(Word.ERROR_MAX_FILES) + " " +  maxNumberOfFiles, showStageOnErrorClose);
			}
		}
		
		private function fileSelect(event:Event):void {
			//check over the file(s) to see if they are ok
			selectedFiles = event.target.fileList;
			var file:FileReference;
			
			//setup the extra stuff that needs to go with the URL
			
			//make sure they didn't try and upload more files than they are allowed
			if(selectedFiles.length <= maxNumberOfFiles){
				//loop over the files to make sure we are golden
				for(var i:int = 0; i < selectedFiles.length; i++){
					file = selectedFiles[i];
					
					if(Math.ceil(file.size/1024) <= maxUploadFileSize){
						//make sure the file extension is good
						if(file.type.toLowerCase() == ".jpg" || file.type.toLowerCase() == ".jpeg" || file.type.toLowerCase() == ".gif" || file.type.toLowerCase() == ".png"){
							//add the amount to the total amount that needs to be transfered
							//totalDataToTransfer += Math.ceil(file.size/1024);
							
							//add it to the progress
							//progress[file.name] = 0;
							
							//fire the onSelect
							onSelect(file, i, showProgress);
							totalFilesSelected++;
							
							//upload the file
							file.upload(uploadURL, "fileFromFlash");
							file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, traceFile, false, 0, true);
							file.addEventListener(HTTPStatusEvent.HTTP_STATUS, traceFile, false, 0, true);
							file.addEventListener(IOErrorEvent.IO_ERROR, traceFile, false, 0, true);
							file.addEventListener(SecurityErrorEvent.SECURITY_ERROR, traceFile, false, 0, true);
						}else{
							//throw an error about the file extension
							DefaultDialog.show("<b>" + file.name + "</b><br><br>" + Language.main(Word.ERROR_FILE_TYPE), showStageOnErrorClose);
						}
					}else{
						//the file size was too large. throw an error.
						DefaultDialog.show("<b>" + file.name + " - " + Math.ceil(file.size/1024) + " KB</b><br><br>" + Language.main(Word.ERROR_FILE_SIZE)+" <b>"+maxUploadFileSize+" KB</b>", showStageOnErrorClose);
					}
				}
			}else{
				//tell them they have already attached the max number
				DefaultDialog.show(Language.main(Word.ERROR_MAX_FILES) + " " +  maxNumberOfFiles, showStageOnErrorClose);
			}
		}
		
		private function traceFile(event:Event):void {
			trace("FILE EVENT:", event);
		}
	}
}